<?php

namespace App\Http\Controllers\Api;

use App\Services\RSADecrypter;
use App\Services\AESCrypter;
use App\Http\Controllers\ApiController;
use Illuminate\Http\Request;
use App\Models\User;

class AuthController extends ApiController
{
    /**
     * 登录
     * POST /api/auth/login
     */
    public function login(Request $request)
    {
        $username = $request->input('username');
        $password = $request->input('password');
        // $lucky = $request->input('lucky');
        $enkey = $request->input('enkey');
        $iv = $request->input('iv');

        $rsaDecrypter = new RSADecrypter(ROOT_PATH . '/resources/keys/private');
        $key = $rsaDecrypter->decrypt($enkey);

        $aesCrypter = new AESCrypter($key, $iv);
        $password = $aesCrypter->decrypt($password);

        $user = User::where('username', $username)->first();
        if ($user && password_verify($password, $user->password)) {
            // if ($user->lucky == $lucky) {
            //     return $this->error('幸运数字不能跟上次一样哦。');
            // }
            // $user->lucky = $lucky;
            $user->save();
            $request->session()->put('user', $user->id);
            $request->session()->put('status', 0);
            return $this->success($user);
        }

        return $this->error('用户名或密码错误');
    }

    /**
     * 获取当前用户状态
     * GET /api/auth/info
     */
    public function getUserInfo()
    {
        $session = app('session');
        if ($session->has('user')) {
            $user = User::where('id', $session->get('user'))->first();
            return $this->success([
                'logged_in' => true,
                'info' => $user
            ]);
        } else {
            return $this->success([
                'logged_in' => false
            ]);
        }
    }

    /**
     * 开始出题
     * PUT /api/auth/status
     */
    public function start(Request $request)
    {
        // if ($request->session()->has('user')) {
        //     // $lucky = $request->input('lucky');
        //     $id = $request->session()->get('user');
        //     $user = User::where('id', $id)->where()->first();
        //     $partner = User::where('group', $user->group)->where('id', '<>', $id)->first();
        //     if ($partner->lucky == $lucky) {
        //         $request->session()->put('status', 1);
        //         return $this->success();
        //     } else {
        //         return $this->error('你怎么连队友的幸运数字都不知道呢？');
        //     }
        // } else {
        //     return $this->error('你还没登录呢');
        // }
    }

    /**
     * 登出
     * DELETE /api/auth/logout
     */
    public function logout(Request $request)
    {
        $request->session()->flush();
        return $this->success();
    }

    /**
     * 获取RSA公钥
     * GET /api/auth/key
     */
    public function getPublicKey()
    {
        $publicKey = file_get_contents(ROOT_PATH . '/resources/keys/public');
        return $this->success($publicKey);
    }
}
